 ///
 /// @file    io.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-24 16:03:48
 ///
 
#include <limits>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::string;

void printStreamStatus(std::istream & is)
{
	cout << "is's badbit: " << is.bad() << endl;
	cout << "is's failbit: " << is.fail() << endl;
	cout << "is's eofbit: " << is.eof() << endl;
	cout << "is's goodbit: " << is.good() << endl;
}
 
void test0() 
{
	int number = 0;
	//检查流的状态
	printStreamStatus(cin);
	cin >> number;
	printStreamStatus(cin);
	cout << "number:" << number << endl;
	
	//重置流的状态
	cin.clear();
	//清空缓冲区
	cin.ignore(1024, '\n');
	cout << "\n重置流的状态:" << endl;
	printStreamStatus(cin);

	string s1;
	cin >> s1;
	cout << "s1:" << s1 << endl;
} 

//一般情况下，当看到函数形参是非const左值引用时，
//可以认为该参数会进行修改，作为传入传出参数
void readInteger(int & num)
{
	cout << "pls input a valid interger!\n";
	//逗号表达式:它的返回值只与最后一个子表达式有关
	//如果是true，整个表达式的值为true;否则为false
	while(cin >> num, !cin.eof())
	{
		if(cin.bad()) {
			cout << "stream has corrupted!\n" << endl;
			return;
		} else if(cin.fail()) {
			cin.clear();
			cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
			cout << "pls input a valid interger!\n";
			continue;
		} else {
			cout << "num:" << num << endl;
			break;
		}
	}
}

void test1()
{
	int number = 0;
	readInteger(number);
	cout << "number:" << number << endl;
}

 
int main(void)
{
	/* test0(); */
	test1();
	return 0;
}











